<?php
namespace Home\Controller;
use Common\Library\BusinessException;
use Common\Library\Constant;
use Common\Vendor\Hook\BaseHook;
use Think\Cache\Driver\Redis;
use Think\Controller;
use Common\Library\Http\Request;
use Common\Library\Http\Response;
use Think\Log;


class CommonToolsController extends Controller {
    protected $unsRequestHost = 'http://114.80.54.73:8081'; //银生宝正式服//
    protected $unsContractId = '2120170417132156001';
    protected $unsAccountId = '2120170417132156001';
    protected $unsKeys = 'huoyan2020bs';
    protected $unsResponseHost = 'http://api.huoyanzichan.com'; //51部署地址
    //给客户打款
    public function userWithdrawls(){
        //--5--1  |没有放款
        // echo '客户打款';
        $cutomer_id = I('get.customer_id');
        $map = [];
        $map['customer_id'] = $cutomer_id;
        $map['type'] = 5;
        $map['status'] = 1;
        //
        $data = M('consume_history')->field('id, customer_id')->where($map)->order('id  desc')->find();//->join("left join customer_bill_pay_log cbpl on cbpl.consume_id = ch.id")
        $consume_id = $data['id'];
        $customerPayLogSelect = M("customer_pay_log")->field("order_id")->where("consume_id = $consume_id")->select();
        // var_dump($customerPayLogSelect);die;


        $consume_id = $data['id'];
        $map1['customer_id'] = $cutomer_id;
        $map1['type'] = 4;
        $map1['status'] = 12;
        $data1 = M('consume_history')->field('id,customer_id,amount')->where($map1)->order('id  desc')->find();
        // ----if(5-1){====
        //}
        //
        if (count($customerPayLogSelect) == 1) {
            foreach ($customerPayLogSelect as $key => $value) {
                $order_id = $value['order_id'];
                $codeStatus = $this->unsFustatus($order_id);
                if ($codeStatus['result_code'] == 2002) {
                    $set_data = [
                        'cash_amount'   =>  $data1['amount'],
                        'balance_cash_amount'   =>  $data1['amount'],
                        'balance_prepaid'       =>  0
                    ];
                    $setCustomerRes = M("Customer")->where("id = '$cutomer_id'")->setField($set_data);
                    // echo "<br/>";
                    $delRes = M('consume_history')->where("id = '$consume_id'")->delete();
                    // echo "<br/>";
                    Log::pay_write('userWithdrawls*****|consume_id|'. $consume_id .'|对应一笔交易流水customerBillPayLog|处理结果|setCustomerRes|'. $setCustomerRes ."|delRes|". $delRes);
                } else {
                   Log::pay_write('userWithdrawls*****|consume_id|'. $consume_id .'|对应一笔交易流水customerBillPayLog|不处理|codeStatus|'. json_encode($codeStatus) ."|"); 
                }
            }
            
        } elseif (count($customerPayLogSelect) == 0) {
            Log::pay_write('userWithdrawls*****|consume_id|'. $consume_id .'|无对应交易流水customerBillPayLog');
        } elseif (count($customerPayLogSelect) > 1) {
            Log::pay_write('userWithdrawls*****|consume_id|'. $consume_id .'|对应多笔交易流水customerBillPayLog');
        }
        //-----cutoemr_id----2002交易不存在
        //---重新提现 ---5-1干掉 --
        //--customer cash_Amount repalalance _  dpaeaXX =0


        // var_dump($data);
    }
	//http://api.huoyanzichan.com/Home/CommonTools/findUser
//    public function findUser(){
//                //$mobile='18816179882';
//		$mobile="15995427732";
//                $data=M('customer',null)->where(['mobile'=>$mobile])->find();
//                echo json_encode($data);
//		$userid=$data['id'];
//		$data=M('consume_history',null)->where(['customer_id'=>$data['id'=>$userid]])->select();
//		echo json_encode($data);
//		$customerPayLogSelect = M("customer_pay_log")->field("order_id")->where("customer_id = $")->select()
//		;
//		echo json_encode($customerPayLogSelect);
//
//        }

    //查询代付状态
    //http://api.huoyanzichan.com/Home/CommonTools/searchDaifuStatus?orderId=171112072904266536
    public function  searchDaifuStatus(){
           $orderId=I('get.orderId');
            $this->unsFustatus($orderId);
    }
    //查询代扣状态
    public function  searchDaikouStatus(){
        $orderId=I('get.orderId');
        $this->unsPaystatu($orderId);
    }
    //实际交易成功是否成功
    public function unsPaystatu($orderId) {
        $url = $this->unsRequestHost.'/unspay-external/delegateCollect/queryOrderStatus';
        $xml_data = array(
            'accountId'=>$this->unsAccountId,
            'orderId'=>$orderId, //14881805185186
        );
        $sign = $this->unsGenSign($xml_data);
        $xml_data['mac'] = $sign;
        $xml_data = http_build_query($xml_data);
        Log::pay_write('*****订单号：'.$orderId.'用户 代扣 查询交易是否成功|请求数据：'.json_encode($xml_data));
        $result = $this->unsCurlPost($url,$xml_data);
        Log::pay_write('订单号'.$orderId.'用户 代扣  实际还款返回结果：'.$result);
        echo '订单号'.$orderId.'用户 代扣  实际还款返回结果：'.$result.'<br/>';
        $result_arr = json_decode($result,true);
        return $result_arr;
    }
    //http://apitest.huoyanzichan.com/Home/CommonTools/bindCardYinshengbao?customer_id=366354
    //绑卡
    public function bindCardYinshengbao(){
        $CustomerId = I('get.customer_id');
        if(!$CustomerId){
            $this->ajaxReturn(['code'=>400,'msg'=>'id  not exists']);
        }
        $map = [];
        $map_ = [];
        $map['customer_id'] = $CustomerId;
        $map_['id'] = $CustomerId;
        //$map['sub_contract_id '] = '123';
        $customer = M('customer')->field('id,mobile,real_name,id_num')->where($map_)->find();
        $data = M('customer_bank_info',null)
                ->field('id,customer_id,card_user_name,sub_contract_id,card_num,reserved_mobile')
                ->where($map)
                ->find();
        if(!$data){
            echo $CustomerId.'子协议号不为123';
        }else{

        }
        echo json_encode($data);
        echo json_encode($customer);
        $card=A('Home/Pay');
        echo $data['card_num'].$data['reserved_mobile'].$data['card_user_name'].$customer['id_num'];
       // die;
        $da=$card->unsBind($data['card_num'],$data['reserved_mobile'],$data['card_user_name'],$customer['id_num']);

        echo '卡号码'.$data['card_num'].'返回结果'.json_encode($da).'<br/>';
        //$d=json_decode($da,true);
        var_dump($da);
        if($da['result_code']=='1005'){
            echo $data['card_num'].'子协议号已存在'.$da;
        }
        //{"result_code":"0000","result_msg":"","subContractId":"9384440"}
        if($da['result_code']=='0000'){
           //subContractId --9384440
            echo '0000';
            echo  json_encode($da);
            $cancel_res = M('customer_bank_info',null)->where(['customer_id'=>$CustomerId])->setField(['sub_contract_id'=>$da['subContractId']]);

        }
        

    }
    //绑卡
    public function unsBind($cardNo,$phoneNo,$name,$idCardNo) {
        $url = $this->unsRequestHost.'/unspay-external/subcontract/signSimpleSubContract';
        //$cardNo = '62220202000473XXX';
        //$phoneNo = '15010258909';
        //$name = '杨XX';
        //$idCardNo = '36242519840213XXXX';
        $xml_data = array(
            'accountId'=>$this->unsAccountId,
            'contractId'=>$this->unsContractId,
            'name'=>$name,
            'phoneNo'=>$phoneNo,
            'cardNo'=>$cardNo,
            'idCardNo'=>$idCardNo,
            'startDate'=>date('Ymd'),
            'endDate'=>'20180301',
        );
        $sign = $this->unsGenSign($xml_data);
        $xml_data['mac'] = $sign;
        $xml_data = http_build_query($xml_data);
        echo $xml_data;
        $result = $this->unsCurlPost($url,$xml_data);
        echo  $result;
        $result_arr = json_decode($result,true);
        Log::rong_write_borrow("绑定卡操作".$result."***");
        return $result_arr;
    }
    //实际代付交易成功是否成功
    public function unsFustatus($orderId) {
        $url = $this->unsRequestHost.'/unspay-external/delegatePay/queryOrderStatus';
        $xml_data = array(
            'accountId'=>$this->unsAccountId,
            'orderId'=>$orderId,
        );
        $sign = $this->unsGenSign($xml_data);
        $xml_data['mac'] = $sign;
        $xml_data = http_build_query($xml_data);
        Log::pay_write('订单号：'.$orderId.'用户代付 查询交易是否成功 请求数据url:'.$url);
        $result = $this->unsCurlPost($url,$xml_data);
         echo '订单号'.$orderId.'用户代付 查询用户实际还款返回结果：'.$result.'<br/>';
        Log::pay_write('订单号'.$orderId.'用户代付 查询用户实际还款返回结果：'.$result);
        $result_arr = json_decode($result,true);
        return $result_arr;//2002
    }
    function unsCurlPost($url,$xml_data) {

        //$header[] = "Content-Type: application/json;charset=utf-8";
        $ch=curl_init($url);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_TIMEOUT, 300);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 300);
        //curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        //curl_setopt($ch, CURLOPT_HTTPHEADER, array('Expect:'));

        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);

        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $xml_data);
        $response = curl_exec($ch);
        if(curl_errno($ch))
        {
            print curl_error($ch);
        }
        curl_close($ch);
        return $response;
    }
    //订单号生成
    public function trade_no() {
        list($usec, $sec) = explode(" ", microtime());
        $usec = substr(str_replace('0.', '', $usec), 0 ,4);
        $str  = rand(10,99);
        return date("ymdHis").$usec.$str;
    }
    function unsGenSign(array $param) {
        //0. 删除原数据中自带的sign值,防止干扰计算结果
        unset($param['sign']);

        foreach ($param as $key => $value) {
            if (is_array($value)) {
                $param[$key] = unsGenSign($value);
            }
        }
        //2. 生成以&符链接的key=value形式的字符串
        $paramString = urldecode(http_build_query($param));
        //3. 拼接我们的服务秘钥，并md5加密
        $sign = strtoupper(md5($paramString .'&key='. $this->unsKeys));
        Log::pay_write('***银生宝加密前的参数'.$paramString .'&key='. $this->unsKeys.'加密后的mac值'.$sign);
        return $sign;
    }





}
